#include "Pet.h"
#include "WeaponBank.h"
#include "PlaneShotStrategy.h"
#include "StrategyBank.h"
#include "Config.h"
#include "MainLayer.h"

Pet::Pet(void)
{
	_plane = NULL;
	_id = NULL;
	_listSupportedWeapon = NULL;
	_strategy = NULL;
	_offset = CCPointZero;
	_targetPosition = CCPointZero;
	_weaponLevel = 1;
}


Pet::~Pet(void)
{
	CC_SAFE_RELEASE(_plane);
	CC_SAFE_RELEASE(_id);
	CC_SAFE_RELEASE(_strategy);
	CC_SAFE_RELEASE(_listSupportedWeapon);
}

bool Pet::init()
{
	if (!BaseObject::init())
		return false;
	setSupportedWeapon(CCArray::create());
	setOffset(ccp(0, 0));

	BaseStrategy* st = StrategyBank::sharedStrategyBank()->createStrategy(STRATEGY_PLANESHOT_1);
	setStrategy(st);
	addChild(st);

	return true;
}

void Pet::onEnter()
{
	BaseObject::onEnter();
	schedule(SEL_SCHEDULE(&Pet::processing));
}

void Pet::onExit()
{
	BaseObject::onExit();
	unschedule(SEL_SCHEDULE(&Pet::processing));
}

void Pet::onShooting( float dt )
{
	if (!_strategy)
		return;
	dynamic_cast<PlaneShotStrategy*>(_strategy)->shoot(dt);
}

int Pet::getWeaponLevel()
{
	return _weaponLevel;
}

void Pet::setWeaponLevel(int val)
{
	val --;
	if (val < 0)
		val = 0;
	if (val >= _listSupportedWeapon->count())
		val = _listSupportedWeapon->count() - 1;

	Weapon* wp = WeaponBank::sharedWeaponBank()->getWeapon((char*)dynamic_cast<CCString*>(_listSupportedWeapon->objectAtIndex(val))->getCString());
	PlaneShotStrategy* strategy = dynamic_cast<PlaneShotStrategy*>(_strategy);
	strategy->removeChild(strategy->getWeapon());
	strategy->addChild(wp);
	strategy->setWeapon(wp);
	unschedule(SEL_SCHEDULE(&Pet::onShooting));
	if (wp->getTimeDelay() != 0)
		schedule(SEL_SCHEDULE(&Pet::onShooting), wp->getTimeDelay());
}

void Pet::processing( float dt )
{
	setTargetPosition(_plane->getPosition() + _offset);
	CCPoint a =  (_targetPosition - this->getPosition());
	a.x *= 1000;
	a.y *= 1000;
	float c = (a.x * dt * dt)/2;
	float b = (a.y * dt * dt)/2;
	setPositionX(getPositionX() + (a.x * dt * dt)/2);
	setPositionY(getPositionY() + (a.y * dt * dt)/2);
}

void Pet::shoot( Bullet* bullet )
{
	getMainLayer()->addPlayerBullet(bullet);
}
